package com.cskaoyan.wordmemorize.controller.admin;

import com.cskaoyan.wordmemorize.auth.SaAdminCheckPermission;
import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.common.upload.AliOssStorageServiceImpl;
import com.cskaoyan.wordmemorize.dto.admin.*;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.VocCommand;
import com.cskaoyan.wordmemorize.request.VocPageRequest;
import com.cskaoyan.wordmemorize.service.VocService;
import com.cskaoyan.wordmemorize.service.impl.VocServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/voc")
public class AdminVocController {


    @Autowired
    VocService vocService;

    @Resource
    AliOssStorageServiceImpl aliOssStorageService;



    @PostMapping("")
    public Result addVoc(@RequestBody VocCommand vocCommand) {

        vocService.addVoc(vocCommand);

        return Result.ok();
    }

    @DeleteMapping("example/{id}")
    public Result deleteExampleSentence(@PathVariable("id")Long id){
        vocService.deleteExample(id);
        return Result.ok();
    }

    @DeleteMapping("interpretation/{id}")
    public Result deleteInterpretation(@PathVariable("id")Long id){
        vocService.deleteInterpretation(id);
        return Result.ok();
    }

    @DeleteMapping("relation/{id}")
    public Result deleteVocRelation(@PathVariable("id")Long id){
        vocService.deleteVocRelation(id);
        return Result.ok();
    }

    @DeleteMapping("{vocId}")
    @SaAdminCheckPermission("admin:voc:delete")
    public Result deleteVocabulary(@PathVariable("vocId")Long vocId){
        vocService.deleteVocabulary(vocId);
        return Result.ok();
    }

    @GetMapping("list")
    public Result<PageDTO<VocDTO>> getVocList(VocPageRequest vocPageRequest){
        PageDTO<VocDTO> vocDTOPageDTO = vocService.getVocabularies(vocPageRequest);

        return Result.ok(vocDTOPageDTO);
    }

    @GetMapping("relations/{vocId}")
    public Result<List<VocChapBookDTO>> getVocRelations(@PathVariable("vocId")Long vocId){
        List<VocChapBookDTO> vocChapBookDTOList = vocService.getVocRelations(vocId);
        return Result.ok(vocChapBookDTOList);
    }


    /**
     * 修改单词
     * @param vocCommand
     * @return
     */

    @PutMapping("")
    public Result updateVoc(@RequestBody VocCommand vocCommand) {
        System.out.println("voc 更新");
        if (vocCommand == null) {
            return Result.fail();
        }
        vocService.updateVoc(vocCommand);
        return Result.ok();
    }

    /**
     * 批量修改单词
     * @param command
     * @return 删除单词列表
     */
    @DeleteMapping("")
    public Result<List<DeleteVocOperateDTO>> batchDeleteVoc(@RequestBody BatchDeleteCommand command) {
        List<DeleteVocOperateDTO> deleteVocOperateDTOList = new ArrayList<>();
        if (command.getIds().size() == 0) {
            return Result.fail();
        }
        List<DeleteVocOperateDTO> deleteVocOperateDTOS = vocService.deleteVocabularies(command);
        return Result.ok(deleteVocOperateDTOS);


    }

    /**
     * 上传文件到阿里云
     * @param file
     * @return 文件url
     */

    @PostMapping("/file")
    public Result<String> addVocFile(@RequestPart("file") MultipartFile file) {
        String upload = null;
        try {
            upload = aliOssStorageService.upload(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return Result.ok(upload);
    }

    /**
     * 删除阿里云单词读音文件和数据库中的文件url
     * @param name
     * @param type
     * @param id
     * @return
     */

    @DeleteMapping("file/{type}/{id}")
    public Result<DeleteVocFileOperateDTO> deleteVocFile(@RequestParam String name, @PathVariable("type") String type, @PathVariable("id") Long id) {
        if (StringUtils.isAnyBlank(name, type)) {
            return Result.fail();
        }
        DeleteVocFileOperateDTO deleteVocFileOperateDTO = vocService.deleteFile(id, type, name);
        if (deleteVocFileOperateDTO == null) {
            return Result.fail();
        }
        //删除成功才会删除掉阿里云上的文件
        aliOssStorageService.deleteFile(name);
        return Result.ok(deleteVocFileOperateDTO);
    }

    @PostMapping("excel")
    public Result<ExcelAddOperateDTO> addVocByExcel(@RequestPart("vocExcel") MultipartFile file) throws IOException {
        Long employeeId = StpKit.ADMIN.getLoginIdAsLong();
        ExcelAddOperateDTO excelAddOperateDTO = vocService.addVocExcel(file, employeeId);
        return Result.ok(excelAddOperateDTO);
    }
    @PostMapping("excel/validate")
    public Result checkExcelValidate(@RequestPart("vocExcel") MultipartFile file) throws IOException {
        vocService.vocExcelValidate(file);
        return Result.ok();

    }

    /**
     *获取单词上传的excel文件
     * @return
     * @throws IOException
     */
    @GetMapping("/template")
    public ResponseEntity<? extends Object> getExcelTemplate() throws IOException {

        ClassPathResource resource;

        resource = new ClassPathResource("templates/单词上传模版.xlsx");

        // 检查文件是否存在
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 读取文件内容
        InputStream inputStream = resource.getInputStream();
        byte[] fileBytes = IOUtils.toByteArray(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",
                URLEncoder.encode(resource.getFilename(), "UTF-8"));

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileBytes);
    }
}
